<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
* Get Geo Location by given IP address
*
* @access    public
* @param    string
* @return    array
*/
if (!function_exists('get_geolocation')) {
	
	function get_geolocation($ip) {
		$locationJson = file_get_contents("http://freegeoip.net/json/$ip");
		//Use backup server if cannot make a connection
		if (!$locationJson) {

			return false; // Failed to open connection
		} else {
			$result =json_decode($locationJson);
		}
		$flagImagePath = IMAGES_PATH . 'flags/' . strtolower($result->country_code) . '.png';
		$flagImageUrl = IMAGES_URL . 'flags/' . strtolower($result->country_code) . '.png';		
		if (!file_exists($flagImagePath)){
			$flagImageUrl = "http://www.geognos.com/api/en/countries/flag/{$result->country_code}.png";
		}
		return array('city'=>$result->city, 'region_name'=>$result->region_name, 'country_code'=>$result->country_code, 'country_name'=>$result->country_name, 'imageUrl'=> $flagImageUrl);
	}
}